package org.example.jwt.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Calendar;
import java.util.Map;

public class JWTUtils {

    //秘钥
    private static final String SIGN_KEY = "JIUFYXCVPOIWERSPODFPMDIUHSK";
    //过期时间(秒) 有效期一周
    private static int EXPIRE = 7 * 24 * 60 * 60;

    /**
     * 创建token
     * @param payload
     * @return
     */
    public static String createToken(Map<String, Object> payload) {
        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.SECOND, EXPIRE);

        return JWT.create()
                .withPayload(payload)
                .withExpiresAt(instance.getTime())
                .sign(Algorithm.HMAC256(SIGN_KEY));
    }

    /**
     * 验签
     * @param token
     * @return
     */
    public static DecodedJWT verify(String token) {
        return JWT.require(Algorithm.HMAC256(SIGN_KEY)).build().verify(token);
    }


}
